/*
 * Copyright 2009 Brook Smith brook.smith@paradise.net.nz.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.javagenerate.generator.script;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.javagenerate.generator.MethodDefinition;
import org.javagenerate.generator.Parameter;

public class MethodUtils {

	private static Set<String> ACCESSORS = new HashSet<String>();
	static {
		ACCESSORS.add("private");
		ACCESSORS.add("protected");
		ACCESSORS.add("public");
	}

	/**
	 * Convert the textual definition of the method into a MethodDefinition Object
	 * @param tokens
	 * @return
	 */
	public static MethodDefinition parseMethod(List<String> tokens) {
		String accessor = "";
		boolean isStatic = false;
		boolean inParams = false;
		boolean inExceptions = false;
		boolean isFinal = false;
		boolean isAbstract = false;
		String returnType = null;
		MethodDefinition definition = null;
		String type = null;
		for (String string : tokens) {
			if (string.equals(" ")) {
				// just a space
			} else if (ACCESSORS.contains(string)) {
				accessor = string;
			} else if (string.equals("static")) {
				isStatic = true;
			} else if (string.equals("final")) {
				isFinal = true;
			} else if (string.equals("abstract")) {
				isAbstract = true;
			} else if (string.equals("throws")) {
				inExceptions = true;
			} else if (inExceptions) {
				definition.getExceptions().add(string);
			} else if (string.equals("(")) {
				inParams = true;
			} else if (inParams) {
				if (type == null) {
					type = string;
				} else {
					definition.addParameter(new Parameter(string, type));
					type = null;
				}
			} else if (string.equals(",")) {
				// ignore
			} else {
				if (returnType == null) {
					returnType = string;
				} else {
					definition = new MethodDefinition(returnType, string);
					definition.setAbstract(isAbstract);
					definition.setFinal(isFinal);
					definition.setStatic(isStatic);
					definition.setVisability(accessor);
				}
			}
		}

		return definition;
	}
}
